home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 2: Applications / Linux Cubed Series 2 - Applications.iso / editors / emacs / xemacs / xemacs-1.004 / xemacs-1 / xemacs-19.13 / src / search.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-08-18  |  61.8 KB  |  2,095 lines

  1. /* String search routines for XEmacs.
  2.    Copyright (C) 1985, 1986, 1987, 1992, 1993, 1994
  3.    Free Software Foundation, Inc.
  4.    Copyright (C) 1994, 1995 Amdahl Corporation.
  5.  
  6. This file is part of XEmacs.
  7.  
  8. XEmacs is free software; you can redistribute it and/or modify it
  9. under the terms of the GNU General Public License as published by the
  10. Free Software Foundation; either version 2, or (at your option) any
  11. later version.
  12.  
  13. XEmacs is distributed in the hope that it will be useful, but WITHOUT
  14. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15. FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  16. for more details.
  17.  
  18. You should have received a copy of the GNU General Public License
  19. along with XEmacs; see the file COPYING.  If not, write to the Free
  20. Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  21.  
  22. /* Synched up with: FSF 19.28. */
  23.  
  24. /* Hacked on for Mule by Ben Wing, December 1994. */
  25.  
  26. #include <config.h>
  27. #include "lisp.h"
  28.  
  29. #include "buffer.h"
  30. #include "commands.h"
  31. #include "insdel.h"
  32. #include "mule.h"
  33. #include <sys/types.h>
  34. #include "regex.h"
  35. #include "syntax.h"
  36.  
  37. #ifndef MULE_REGEXP
  38. #define EXTENDED_REGEXP_P(x) 0
  39. #endif
  40.  
  41.  
  42. /* We compile regexps into this buffer and then use it for searching. */
  43.  
  44. struct re_pattern_buffer searchbuf;
  45.  
  46. static char search_fastmap[0400];
  47.  
  48. /* Last regexp we compiled */
  49. static Lisp_Object last_regexp;
  50.  
  51. #ifdef MULE_REGEXP
  52. /* Regular expressions used in forward/backward-word */
  53. Lisp_Object Vforward_word_regexp, Vbackward_word_regexp;
  54.  
  55. /* Version number of system internal regexp compiler and interpreter. */
  56.  
  57. Lisp_Object Vregexp_version;
  58. #endif /* MULE_REGEXP */
  59.  
  60. /* Every call to re_match, etc., must pass &search_regs as the regs argument
  61.    unless you can show it is unnecessary (i.e., if re_match is certainly going
  62.    to be called again before region-around-match can be called).  
  63.  
  64.    Since the registers are now dynamically allocated, we need to make
  65.    sure not to refer to the Nth register before checking that it has
  66.    been allocated by checking search_regs.num_regs.
  67.  
  68.    The regex code keeps track of whether it has allocated the search
  69.    buffer using bits in searchbuf.  This means that whenever you
  70.    compile a new pattern, it completely forgets whether it has
  71.    allocated any registers, and will allocate new registers the next
  72.    time you call a searching or matching function.  Therefore, we need
  73.    to call re_set_registers after compiling a new pattern or after
  74.    setting the match registers, so that the regex functions will be
  75.    able to free or re-allocate it properly.  */
  76. static struct re_registers search_regs;
  77. #ifdef NEW_SYNTAX
  78. # define SEARCH_NREGS(x) (x)->num_regs
  79. #else
  80. # define SEARCH_NREGS(x) RE_NREGS
  81. #endif
  82.  
  83.  
  84. /* The buffer in which the last search was performed, or
  85.    Qt if the last search was done in a string;
  86.    Qnil if no searching has been done yet.  */
  87. static Lisp_Object last_thing_searched;
  88.  
  89. /* error condition signalled when regexp compile_pattern fails */
  90. Lisp_Object Qinvalid_regexp;
  91.  
  92. static void set_search_regs (Bytind, Bytecount);
  93.  
  94. static void
  95. matcher_overflow (void)
  96. {
  97. #if 0 /* This is too much of a compatibility problem. */ /* #### GAG! */
  98.   error ("Stack overflow in regexp matcher");
  99. #endif
  100. }
  101.  
  102. /* Compile a regexp and signal a Lisp error if anything goes wrong.  */
  103. int
  104. compile_pattern (Lisp_Object pattern, struct re_pattern_buffer *bufp,
  105.          struct re_registers *regp, char *translate,
  106.          int backward, int no_error)
  107. {
  108.   /* !!#### This function has not been Mule-ized */
  109.   CONST char *val;
  110.  
  111.   if (EQ (pattern, last_regexp)
  112.       && translate == bufp->translate
  113. #ifdef MULE_REGEXP
  114.       && NILP (current_buffer->mc_flag) == !bufp->mc_flag
  115.       && (!bufp->syntax_version
  116.       || bufp->syntax_version == syntax_table_version)
  117.       && (!bufp->category_version
  118.       || bufp->category_version == category_table_version)
  119. #endif /* MULE_REGEXP */
  120.     )
  121.     return 1;
  122.  
  123. #ifdef MULE_REGEXP
  124.   if (CONSP (pattern))            /* pre-compiled regexp */
  125.     {
  126.       Lisp_Object compiled;
  127.  
  128.       val = 0;
  129.       pattern = XCAR (pattern);
  130.       if (CONSP (pattern)
  131.       && (compiled = backward ? XCDR (pattern) : XCAR (pattern))
  132.       && XTYPE (compiled) == Lisp_Vector
  133.       && XVECTOR (compiled)->size == 4)
  134.     {
  135.       /* set_pattern will set bufp->allocated to NILP */
  136.       set_pattern (compiled, bufp, translate);
  137.       return 1;
  138.     }
  139.  
  140.       val = "Invalid pre-compiled regexp";
  141.       goto invalid_regexp;
  142.     }
  143. #endif /* MULE_REGEXP */
  144.  
  145.   if (no_error)
  146.     {
  147.       if (!STRINGP (pattern))
  148.     return 0;
  149.     }
  150.   else
  151.     CHECK_STRING (pattern, 0);
  152.  
  153.   last_regexp = Qnil;
  154.   bufp->translate = translate;
  155. #ifdef MULE_REGEXP
  156.   bufp->syntax_version = bufp->category_version = 0;
  157.   /* 
  158.      'bufp->allocated == 0' means bufp->buffer points to pre-compiled pattern
  159.      in a lisp string, which should not be 'realloc'ed. */
  160.   if (bufp->allocated == 0) bufp->buffer = 0; 
  161. #endif /* MULE_REGEXP */
  162.  
  163.   val = re_compile_pattern ((char *) string_data (XSTRING (pattern)),
  164.                 string_length (XSTRING (pattern)),
  165.                 bufp);
  166.   if (val)
  167.     {
  168. #ifdef MULE_REGEXP
  169.     invalid_regexp:
  170. #endif /* MULE_REGEXP */
  171.       if (no_error)
  172.     return 0;
  173.       else
  174.     signal_error (Qinvalid_regexp, list1 (build_string (val)));
  175.     }
  176.   last_regexp = pattern;
  177. #ifdef EMACS19_REGEXP
  178.   /* Advise the searching functions about the space we have allocated
  179.      for register data.  */
  180.   if (regp)
  181.     re_set_registers (bufp, regp, regp->num_regs, regp->start, regp->end);
  182. #endif
  183.   return 1;
  184. }
  185.  
  186. #ifdef MULE_REGEXP
  187. /* Set a pre-compiled pattern into a pattern buffer */
  188. /* pattern is a list of strings:
  189.     compiled_code, fastmap, syntax_fastmap, category_fastmap */
  190. set_pattern (Lisp_Object pattern, struct re_pattern_buffer *bufp,
  191.          char *translate)
  192. {
  193.   /* !!#### This function has not been Mule-ized */
  194.  Lisp_Object temp;
  195.  
  196.   if (bufp->allocated != 0)
  197.     {
  198.       /*
  199.     Coming here means that this buffer was used to hold
  200.     an old-style pattern.  Because new-style pattern is not
  201.     self-destructive, we only have to set pointer.
  202.     Instead, to avoid it being freed later,
  203.     bufp->allocated should be set to 0.
  204.     */
  205.       xfree (bufp->buffer);
  206.       bufp->allocated = 0;
  207.     }
  208.   temp = vector_data (XVECTOR (pattern))[0];
  209.   bufp->buffer = (char *) string_data (XSTRING (temp));
  210.   bufp->used = string_length (XSTRING (temp));
  211.   bufp->translate = translate;
  212.   /* set fastmap */
  213.   bufp->mc_flag = !NILP (current_buffer->mc_flag);
  214.  
  215. #ifdef EMACS19_REGEXP
  216.   bufp->short_flag = 0;
  217.   bufp->no_empty = 0;
  218.  
  219.   bufp->regs_allocated = REGS_UNALLOCATED;
  220.   bufp->re_nsub = 0;                
  221.   bufp->no_sub = 0;
  222.   bufp->newline_anchor = 1;
  223.  
  224.   bufp->syntax = 0;
  225.   bufp->not_bol = bufp->not_eol = 0;
  226. #endif /* EMACS19_REGEXP */
  227.  
  228.   {
  229.     Lisp_Object fmap, syntax_fmap, category_fmap;
  230.     char *fastmap = bufp->fastmap;
  231.     int i;
  232.     unsigned char ch;
  233.  
  234.     bufp->fastmap_accurate = 1;
  235.  
  236.     fmap = vector_data (XVECTOR (pattern))[1];
  237.     if (NILP (fmap) && NILP (syntax_fmap) && NILP (category_fmap))
  238.       {
  239.     bufp->can_be_null = 1;
  240.       }
  241.     else
  242.       {
  243.     bufp->can_be_null = 0;
  244.     memset (fastmap, 0, 256);
  245.     if (STRINGP (fmap))
  246.       memcpy (fastmap, string_data (XSTRING (fmap)),
  247.           string_length (XSTRING (fmap)));
  248.  
  249.     syntax_fmap = vector_data (XVECTOR (pattern))[2];
  250.     if (STRINGP (syntax_fmap))
  251.       {
  252.         for (ch = 0; ch < 0x80; ch++)
  253.           if (!fastmap[ch]
  254.           && string_char (XSTRING (syntax_fmap),
  255.                   syntax_code_spec[(char) SYNTAX (ch)]))
  256.         fastmap[ch] = 1;
  257.         bufp->syntax_version = syntax_table_version;
  258.       }
  259.     else
  260.       bufp->syntax_version = 0;
  261.  
  262.     category_fmap = vector_data (XVECTOR (pattern))[3];
  263.     if (STRINGP (category_fmap))
  264.       {
  265.         char str[96], *p;
  266.         int not_category_spec = 0;
  267.  
  268.         for (i = 32; i < 128; i++)
  269.           if (string_char (XSTRING (category_fmap), i) == 2)
  270.         {
  271.           not_category_spec = 1;
  272.           break;
  273.         }
  274.         for (ch = 0; ch < 0x80; ch++)
  275.           {
  276.         if (!fastmap[ch])
  277.           {
  278.             pack_mnemonic_string
  279.               (char_category (ch, current_buffer->category_table),
  280.                str);
  281.             if (not_category_spec)
  282.               {
  283.             for (p = str; *p; p++)
  284.               if (string_char (XSTRING (category_fmap), *p) != 2)
  285.                 {
  286.                   fastmap[ch] = 1;
  287.                   break;
  288.                 }
  289.               }
  290.             else
  291.               {
  292.             for (p = str; *p; p++)
  293.               if (string_char (XSTRING (category_fmap), *p) == 1)
  294.                 {
  295.                   fastmap[ch] = 1;
  296.                   break;
  297.                 }
  298.               }
  299.           }
  300.           }
  301.         bufp->category_version = category_table_version;
  302.       }
  303.     else
  304.       bufp->category_version = 0;
  305.  
  306.     if (bufp->mc_flag
  307.         && (STRINGP (syntax_fmap) || STRINGP (category_fmap))
  308.       {
  309.         for (ch = 0x80; ch < 0xA0; ch++)
  310.           fastmap[ch] = 1;
  311.       }
  312.       }
  313.   }
  314.    Force 're-compile-pattern' when compile_pattern is called next time. */
  315.   last_regexp = Qnil;
  316. }
  317. #endif /* MULE_REGEXP */
  318.  
  319. /* Error condition used for failing searches */
  320. Lisp_Object Qsearch_failed;
  321.  
  322.  
  323. DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 2, 0,
  324.   "Return t if text after point matches regular expression PAT.\n\
  325. This function modifies the match data that `match-beginning',\n\
  326. `match-end' and `match-data' access; save and restore the match\n\
  327. data if you want to preserve them.\n\
  328. If support for Mule regexps was compiled into this Emacs, and optional\n\
  329. second arg BACK is non-nil and PAT is a pre-compiled pattern,\n\
  330. PAT is looked backward from point.")
  331.   (string, back)
  332.      Lisp_Object string, back;
  333. {
  334.   /* !!#### This function has not been Mule-ized */
  335.   Lisp_Object val;
  336.   Bytind p1, p2;
  337.   Bytecount s1, s2;
  338.   int i;
  339.   struct buffer *buf = current_buffer;
  340.  
  341.   compile_pattern (string, &searchbuf, &search_regs,
  342.            (!NILP (buf->case_fold_search)
  343.             ? string_ext_data (XSTRING (buf->downcase_table))
  344.                     : 0), !NILP (back), 0);
  345.  
  346.   /* Backward search requires extended regexp. */
  347.   if (!NILP (back) && !EXTENDED_REGEXP_P (&searchbuf))
  348.     error ("Can't look backward with this pattern");
  349.  
  350.   /* Get pointers and sizes of the two strings
  351.      that make up the visible portion of the buffer. */
  352.  
  353.   p1 = BI_BUF_BEGV (buf);
  354.   p2 = BI_BUF_CEILING_OF (buf, p1);
  355.   s1 = p2 - p1;
  356.   s2 = BI_BUF_ZV (buf) - p2;
  357.   
  358.   QUIT;
  359.  
  360.   /* mstop, the 8th arg of re_match_2 is offset from BEGV.  So, when */
  361.   /* backward search, it should be BEGV - BEGV, ie. 0 */
  362.   i = re_match_2 (&searchbuf, (unsigned char *) BI_BUF_BYTE_ADDRESS (buf, p1),
  363.           s1, BI_BUF_BYTE_ADDRESS (buf, p2), s2,
  364.           BI_BUF_PT (buf) - BI_BUF_BEGV (buf), &search_regs,
  365.           !NILP (back) ? 0 : BI_BUF_ZV (buf) - BI_BUF_BEGV (buf)
  366. #ifdef MULE_REGEXP
  367.           , !NILP (back)
  368. #endif
  369. );
  370.   if (i == -2)
  371.     matcher_overflow ();
  372.  
  373.   val = (0 <= i ? Qt : Qnil);
  374.   for (i = 0; i < SEARCH_NREGS (&search_regs); i++)
  375.     if (search_regs.start[i] >= 0)
  376.       {
  377.     search_regs.start[i] += BI_BUF_BEGV (buf);
  378.     search_regs.end[i] += BI_BUF_BEGV (buf);
  379.       }
  380.   XSETBUFFER (last_thing_searched, buf);
  381.   return val;
  382. }
  383.  
  384. DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
  385.   "Return index of start of first match for REGEXP in STRING, or nil.\n\
  386. If third arg START is non-nil, start search at that index in STRING.\n\
  387. For index of first char beyond the match, do (match-end 0).\n\
  388. `match-end' and `match-beginning' also give indices of substrings\n\
  389. matched by parenthesis constructs in the pattern.")
  390.   (regexp, string, start)
  391.      Lisp_Object regexp, string, start;
  392. {
  393.   /* !!#### This function has not been Mule-ized */
  394.   int val;
  395.   int s;
  396.   struct buffer *buf = current_buffer;
  397.  
  398.   CHECK_STRING (string, 1);
  399.  
  400.   if (NILP (start))
  401.     s = 0;
  402.   else
  403.     {
  404.       Bytecount len = string_length (XSTRING (string));
  405.  
  406.       CHECK_INT (start, 2);
  407.       s = XINT (start);
  408.       if (s < 0 && -s <= len)
  409.     s = len + s;
  410.       else if (0 > s || s > len)
  411.     args_out_of_range (string, start);
  412.     }
  413.  
  414.   compile_pattern (regexp, &searchbuf, &search_regs,
  415.            (!NILP (buf->case_fold_search)
  416.                     ? (char *) string_data (XSTRING (buf->downcase_table))
  417.                     : 0), 0, 0);
  418.   QUIT;
  419.   val = re_search (&searchbuf,
  420.                    (char *) string_data (XSTRING (string)),
  421.                    string_length (XSTRING (string)),
  422.                    s,
  423.                    string_length (XSTRING (string)) - s, 
  424.                    &search_regs);
  425.   last_thing_searched = Qt;
  426.   if (val == -2)
  427.     matcher_overflow ();
  428.   if (val < 0) return Qnil;
  429.   return make_number (val);
  430. }
  431.  
  432.  
  433. /* Match REGEXP against STRING, searching all of STRING,
  434.    and return the index of the match, or negative on failure.
  435.    This does not clobber the match data.  */
  436.  
  437. Bytecount
  438. fast_string_match (Lisp_Object regexp, CONST Bufbyte *nonreloc,
  439.            Lisp_Object reloc, Bytecount offset,
  440.            Bytecount length, int no_error, int no_quit)
  441. {
  442.   int val;
  443.   Bufbyte *newnonreloc = (Bufbyte *) nonreloc;
  444.  
  445.   if (!compile_pattern (regexp, &searchbuf, 0, 0, 0, no_error))
  446.     return -1; /* will only do this when no_error */
  447.   if (!no_quit)
  448.     QUIT;
  449.   else
  450.     no_quit_in_re_search = 1;
  451.  
  452.   fixup_internal_substring (nonreloc, reloc, offset, &length);
  453.  
  454.   if (!NILP (reloc))
  455.     {
  456.       if (no_quit)
  457.     newnonreloc = string_data (XSTRING (reloc));
  458.       else
  459.     {
  460.       /* QUIT could relocate RELOC.  Therefore we must alloca()
  461.          and copy.  No way around this except some serious
  462.          rewriting of re_search(). */
  463.       newnonreloc = (Bufbyte *) alloca (length);
  464.       memcpy (newnonreloc, string_data (XSTRING (reloc)), length);
  465.     }
  466.     }
  467.  
  468.   val = re_search (&searchbuf, (char *) newnonreloc + offset, length, 0,
  469.            length, 0);
  470.  
  471.   no_quit_in_re_search = 0;
  472.   return val;
  473. }
  474.  
  475. /* Search in BUF for COUNT instances of the character TARGET, starting
  476.    at START and stopping at LIMIT.  If COUNT is negative, search backwards.
  477.    If LIMIT is <= 0, stop at end of accessible region of buffer (or
  478.    beginning of accessible region, if COUNT is negative).
  479.  
  480.    If we find COUNT instances, set *SHORTAGE to zero, and return the
  481.    position after the COUNTth match.  Note that for reverse motion
  482.    this is not the same as the usual convention for Emacs motion commands.
  483.  
  484.    If we don't find COUNT instances before reaching LIMIT, set *SHORTAGE
  485.    to the number of TARGETs left unfound, and return the end of the
  486.    buffer we bumped up against.
  487.  
  488.    If ALLOW_QUIT is non-zero, call QUIT periodically. */
  489.  
  490. Bufpos
  491. scan_buffer (struct buffer *buf, Emchar target, Bufpos start, Bufpos limit,
  492.          int count, int *shortage, int allow_quit)
  493. {
  494.   Bytind lim = limit > 0 ? bufpos_to_bytind (buf, limit) :
  495.     ((count > 0) ? BI_BUF_ZV (buf) : BI_BUF_BEGV (buf));
  496.   Bytind st = bufpos_to_bytind (buf, start);
  497.  
  498.   assert (count != 0);
  499.  
  500.   if (shortage)
  501.     *shortage = 0;
  502.   
  503.   if (count > 0)
  504.     {
  505. #ifdef MULE
  506.       /* Due to the Mule representation of characters in a buffer,
  507.      we can simply search for characters in the range 0 - 127
  508.      directly.  For other characters, we do it the "hard" way.
  509.      Note that this way works for all characters but the other
  510.      way is faster. */
  511.       if (target >= 0200)
  512.     {
  513.       while (st < lim && count > 0)
  514.         {
  515.           if (BI_BUF_FETCH_CHAR (buf, st) == target)
  516.         count--;
  517.           INC_BYTIND (buf, st);
  518.         }
  519.     }
  520.       else
  521. #endif
  522.     {
  523.       while (st < lim && count > 0)
  524.         {
  525.           Bytind ceil;
  526.           Bufbyte *bufptr;
  527.           
  528.           ceil = BI_BUF_CEILING_OF (buf, st);
  529.           ceil = min (lim, ceil);
  530.           bufptr = memchr (BI_BUF_BYTE_ADDRESS (buf, st), (int) target,
  531.                    ceil - st);
  532.           if (bufptr)
  533.         {
  534.           count--;
  535.           st = BI_BUF_PTR_BYTE_POS (buf, bufptr) + 1;
  536.         }
  537.           else
  538.         st = ceil;
  539.         }
  540.     }
  541.  
  542.       if (shortage)
  543.     *shortage = count;
  544.       if (allow_quit)
  545.     QUIT;
  546.       return bytind_to_bufpos (buf, st);
  547.     }
  548.   else
  549.     {
  550. #ifdef MULE
  551.       if (target >= 0200)
  552.     {
  553.       while (st > lim && count < 0)
  554.         {
  555.           DEC_BYTIND (buf, st);
  556.           if (BI_BUF_FETCH_CHAR (buf, st) == target)
  557.         count++;
  558.         }
  559.     }
  560.       else
  561. #endif
  562.     {
  563.       while (st > lim && count < 0)
  564.         {
  565.           Bytind floor;
  566.           Bufbyte *bufptr;
  567.           Bufbyte *floorptr;
  568.           
  569.           floor = BI_BUF_FLOOR_OF (buf, st);
  570.           floor = max (lim, floor);
  571.           /* No memrchr() ... */
  572.           bufptr = BI_BUF_BYTE_ADDRESS_BEFORE (buf, st);
  573.           floorptr = BI_BUF_BYTE_ADDRESS (buf, floor);
  574.           while (bufptr >= floorptr)
  575.         {
  576.           st--;
  577.           /* At this point, both ST and BUFPTR refer to the same
  578.              character.  When the loop terminates, ST will
  579.              always point to the last character we tried. */
  580.           if (* (unsigned char *) bufptr == (unsigned char) target)
  581.             {
  582.               count++;
  583.               break;
  584.             }
  585.           bufptr--;
  586.         }
  587.         }
  588.     }
  589.  
  590.       if (shortage)
  591.     *shortage = -count;
  592.       if (allow_quit)
  593.     QUIT;
  594.       if (count)
  595.     return bytind_to_bufpos (buf, st);
  596.       else
  597.     {
  598.     /* We found the character we were looking for; we have to return
  599.        the position *after* it due to the strange way that the return
  600.        value is defined. */
  601.       INC_BYTIND (buf, st);
  602.       return bytind_to_bufpos (buf, st);
  603.     }
  604.     }
  605. }
  606.  
  607. Bufpos
  608. find_next_newline_no_quit (struct buffer *buf, Bufpos from, int cnt)
  609. {
  610.   return scan_buffer (buf, '\n', from, 0, cnt, (int *) 0, 0);
  611. }
  612.  
  613. Bufpos
  614. find_next_newline (struct buffer *buf, Bufpos from, int cnt)
  615. {
  616.   return scan_buffer (buf, '\n', from, 0, cnt, (int *) 0, 1);
  617. }
  618.  
  619. static Lisp_Object
  620. skip_chars (struct buffer *buf, int forwardp, int syntaxp,
  621.         Lisp_Object string, Lisp_Object lim)
  622. {
  623.   /* !!#### This function has not been Mule-ized */
  624.   unsigned char *p, *pend;
  625.   /* jwz: c must be bigger than char, else (skip-chars-forward "\200-\377")
  626.      loops while trying to fill fastmap, as c++ wraps when c == 255. */
  627.   unsigned int c;
  628.   unsigned char fastmap[0400];
  629.   int negate = 0;
  630. #ifdef MULE_REGEXP
  631.   unsigned char *b;
  632.   struct compile_charset_information info, *ip = &info;
  633. #endif /* MULE_REGEXP */
  634.   int i;
  635.   Lisp_Object syntax_table = buf->syntax_table;
  636.  
  637.   CHECK_STRING (string, 0);
  638.  
  639.   if (NILP (lim))
  640.     XSETINT (lim, forwardp ? BUF_ZV (buf) : BUF_BEGV (buf));
  641.   else
  642.     CHECK_INT_COERCE_MARKER (lim, 1);
  643.  
  644.   /* In any case, don't allow scan outside bounds of buffer.  */
  645.   if (XINT (lim) > BUF_ZV (buf))
  646.     lim = make_number (BUF_ZV (buf));
  647.   if (XINT (lim) < BUF_BEGV (buf))
  648.     lim = make_number (BUF_BEGV (buf));
  649.  
  650.   p = string_data (XSTRING (string));
  651.   pend = p + string_length (XSTRING (string));
  652.   memset (fastmap, 0, sizeof (fastmap));
  653.  
  654.   if (p != pend && *p == '^')
  655.     {
  656.       negate = 1;
  657.       p++;
  658.     }
  659.  
  660. #ifdef MULE_REGEXP
  661.  
  662.   /* !!#### What's going on here? */
  663.   b = (unsigned char *) alloca (1 +  (1 << 8) / 8 + 2 + (pend - p) * 2);
  664.   if (b == 0) error ("not enough memory");
  665.  
  666.   /* Find the characters specified and set their elements of fastmap.  */
  667.  
  668.   init_compile_charset_information (ip, b, p, pend, 0, mc_flag, 1);
  669.  
  670.   if (compile_charset (ip))
  671.     error ("maybe invalid charset");
  672.   b[0] = ip->bitmap_size;
  673.   if (ip->rt_used - ip->range_table)
  674.     {
  675.       b[0] |= 0x80;
  676.       b[ip->bitmap_size+1] = (ip->rt_used - ip->range_table) >> 8;
  677.       b[ip->bitmap_size+2] = (ip->rt_used - ip->range_table) & 0xff;
  678.     }
  679.  
  680.   {
  681.     Bufpos start_point = BUF_PT (buf);
  682.  
  683.     if (forwardp)
  684.       {
  685.     while (BUF_PT (buf) < XINT (lim))
  686.       {
  687.         c = BUF_FETCH_CHAR (buf, BUF_PT (buf));
  688.  
  689.         if (lookup_charset (b, c, 0, 0) == negate)
  690.           break;
  691.  
  692.         BUF_SET_PT (buf, BUF_PT (buf) + 1);
  693.       }
  694.       }
  695.     else
  696.       {
  697.     while (BUF_PT (buf) > XINT (lim))
  698.       {
  699.         Bufpos pos;
  700.  
  701.         pos = BUF_PT (buf) - 1;
  702.         c = BUF_FETCH_CHAR (buf, pos);
  703.  
  704.         if (lookup_charset (b, c, 0, 0) == negate)
  705.           break;
  706.  
  707.         BUF_SET_PT (buf, pos);
  708.       }
  709.       }
  710.  
  711.     QUIT;
  712.     return make_number (BUF_PT (buf) - start_point);
  713.   }
  714.  
  715. #else /* !MULE_REGEXP */
  716.  
  717.   /* Find the characters specified and set their elements of fastmap.
  718.      If syntaxp, each character counts as itself.
  719.      Otherwise, handle backslashes and ranges specially  */
  720.  
  721.   while (p != pend)
  722.     {
  723.       c = *p++;
  724.       if (syntaxp)
  725.     fastmap[c] = 1;
  726.       else
  727.     {
  728.       if (c == '\\')
  729.         {
  730.           if (p == pend) break;
  731.           c = *p++;
  732.         }
  733.       if (p != pend && *p == '-')
  734.         {
  735.           p++;
  736.           if (p == pend) break;
  737.           while (c <= *p)
  738.         {
  739.           fastmap[c] = 1;
  740.           c++;
  741.         }
  742.           p++;
  743.         }
  744.       else
  745.         fastmap[c] = 1;
  746.     }
  747.     }
  748.  
  749.   if (syntaxp && fastmap['-'] != 0)
  750.     fastmap[' '] = 1;
  751.  
  752.   /* If ^ was the first character, complement the fastmap. */
  753.  
  754.   if (negate)
  755.     for (i = 0; i < sizeof fastmap; i++)
  756.       fastmap[i] ^= 1;
  757.  
  758.   {
  759.     Bufpos start_point = BUF_PT (buf);
  760.  
  761.     if (syntaxp)
  762.       {
  763.  
  764.     if (forwardp)
  765.       {
  766.         while (BUF_PT (buf) < XINT (lim)
  767.            && fastmap[(unsigned char)
  768.                               syntax_code_spec[(int) SYNTAX (syntax_table,
  769.                                                              BUF_FETCH_CHAR (buf, BUF_PT (buf)))]])
  770.           BUF_SET_PT (buf, BUF_PT (buf) + 1);
  771.       }
  772.     else
  773.       {
  774.         while (BUF_PT (buf) > XINT (lim)
  775.            && fastmap[(unsigned char) 
  776.                               syntax_code_spec[(int) SYNTAX (syntax_table,
  777.                                                              BUF_FETCH_CHAR (buf, BUF_PT (buf) - 1))]])
  778.           BUF_SET_PT (buf, BUF_PT (buf) - 1);
  779.       }
  780.       }
  781.     else
  782.       {
  783.     if (forwardp)
  784.       {
  785.         while (BUF_PT (buf) < XINT (lim) && fastmap[BUF_FETCH_CHAR (buf, BUF_PT (buf))])
  786.           BUF_SET_PT (buf, BUF_PT (buf) + 1);
  787.       }
  788.     else
  789.       {
  790.         while (BUF_PT (buf) > XINT (lim) && fastmap[BUF_FETCH_CHAR (buf, BUF_PT (buf) - 1)])
  791.           BUF_SET_PT (buf, BUF_PT (buf) - 1);
  792.       }
  793.       }
  794.     QUIT;
  795.     return make_number (BUF_PT (buf) - start_point);
  796.   }
  797.  
  798. #endif /* MULE_REGEXP */
  799. }
  800.  
  801. DEFUN ("skip-chars-forward", Fskip_chars_forward, Sskip_chars_forward, 1, 3, 0,
  802.   "Move point forward, stopping before a char not in CHARS, or at position LIM.\n\
  803. CHARS is like the inside of a `[...]' in a regular expression\n\
  804. except that `]' is never special and `\\' quotes `^', `-' or `\\'.\n\
  805. Thus, with arg \"a-zA-Z\", this skips letters stopping before first nonletter.\n\
  806. With arg \"^a-zA-Z\", skips nonletters stopping before first letter.\n\
  807. Returns the distance traveled, either zero or positive.\n\
  808. \n\
  809. Optional argument BUFFER defaults to the current buffer.")
  810.   (chars, lim, buffer)
  811.      Lisp_Object chars, lim, buffer;
  812. {
  813.   return skip_chars (decode_buffer (buffer, 0), 1, 0, chars, lim);
  814. }
  815.  
  816. DEFUN ("skip-chars-backward", Fskip_chars_backward, Sskip_chars_backward, 1, 3, 0,
  817.   "Move point backward, stopping after a char not in CHARS, or at position LIM.\n\
  818. See `skip-chars-forward' for details.\n\
  819. Returns the distance traveled, either zero or negative.\n\
  820. \n\
  821. Optional argument BUFFER defaults to the current buffer.")
  822.   (chars, lim, buffer)
  823.      Lisp_Object chars, lim, buffer;
  824. {
  825.   return skip_chars (decode_buffer (buffer, 0), 0, 0, chars, lim);
  826. }
  827.  
  828.  
  829. DEFUN ("skip-syntax-forward", Fskip_syntax_forward, Sskip_syntax_forward, 1, 3, 0,
  830.   "Move point forward across chars in specified syntax classes.\n\
  831. SYNTAX is a string of syntax code characters.\n\
  832. Stop before a char whose syntax is not in SYNTAX, or at position LIM.\n\
  833. If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.\n\
  834. This function returns the distance traveled, either zero or positive.\n\
  835. \n\
  836. Optional argument BUFFER defaults to the current buffer.")
  837.   (syntax, lim, buffer)
  838.      Lisp_Object syntax, lim, buffer;
  839. {
  840.   return skip_chars (decode_buffer (buffer, 0), 1, 1, syntax, lim);
  841. }
  842.  
  843. DEFUN ("skip-syntax-backward", Fskip_syntax_backward, Sskip_syntax_backward, 1, 3, 0,
  844.   "Move point backward across chars in specified syntax classes.\n\
  845. SYNTAX is a string of syntax code characters.\n\
  846. Stop on reaching a char whose syntax is not in SYNTAX, or at position LIM.\n\
  847. If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.\n\
  848. This function returns the distance traveled, either zero or negative.\n\
  849. \n\
  850. Optional argument BUFFER defaults to the current buffer.")
  851.   (syntax, lim, buffer)
  852.      Lisp_Object syntax, lim, buffer;
  853. {
  854.   return skip_chars (decode_buffer (buffer, 0), 0, 1, syntax, lim);
  855. }
  856.  
  857.  
  858. /* Subroutines of Lisp buffer search functions. */
  859.  
  860. static Bytind search_buffer (Lisp_Object str, Bytind pos, Bytind lim, int n,
  861.                  int RE, unsigned char *trt,
  862.                  unsigned char *inverse_trt);
  863.  
  864. static Lisp_Object
  865. search_command (Lisp_Object string, Lisp_Object bound, Lisp_Object no_error,
  866.         Lisp_Object count, int direction, int RE)
  867. {
  868.   /* !!#### This function has not been Mule-ized */
  869.   int np;
  870.   Bufpos lim;
  871.   long n = direction;
  872.   struct buffer *buf = current_buffer;
  873.  
  874.   if (!NILP (count))
  875.     {
  876.       CHECK_INT (count, 3);
  877.       n *= XINT (count);
  878.     }
  879.  
  880.   /* string is now checked in compile_pattern, which is called from
  881.      search_buffer. */
  882.   if (NILP (bound))
  883.     lim = n > 0 ? BUF_ZV (buf) : BUF_BEGV (buf);
  884.   else
  885.     {
  886.       CHECK_INT_COERCE_MARKER (bound, 1);
  887.       lim = XINT (bound);
  888.       if (n > 0 ? lim < BUF_PT (buf) : lim > BUF_PT (buf))
  889.     error ("Invalid search bound (wrong side of point)");
  890.       if (lim > BUF_ZV (buf))
  891.     lim = BUF_ZV (buf);
  892.       if (lim < BUF_BEGV (buf))
  893.     lim = BUF_BEGV (buf);
  894.     }
  895.  
  896.   np = search_buffer (string, BUF_PT (buf), lim, n, RE,
  897.               (!NILP (buf->case_fold_search)
  898.                ? string_data (XSTRING (buf->case_canon_table)) 
  899.                        : 0),
  900.               (!NILP (buf->case_fold_search)
  901.                ? string_data (XSTRING (buf->case_eqv_table)) 
  902.                        : 0));
  903.  
  904.   if (np <= 0)
  905.     {
  906.       if (NILP (no_error))
  907.     {
  908.       Fsignal (Qsearch_failed, list1 (string));
  909.       return Qnil;
  910.     }
  911.       if (!EQ (no_error, Qt))
  912.     {
  913.       if (lim < BUF_BEGV (buf) || lim > BUF_ZV (buf))
  914.         abort ();
  915.       BUF_SET_PT (buf, lim);
  916.       return Qnil;
  917. #if 0            /* This would be clean, but maybe programs depend on
  918.                a value of nil here.  */
  919.       np = lim;
  920. #endif
  921.     }
  922.  
  923.       else
  924.         return Qnil;
  925.     }
  926.  
  927.   if (np < BUF_BEGV (buf) || np > BUF_ZV (buf))
  928.     abort ();
  929.  
  930.   BUF_SET_PT (buf, np);
  931.  
  932.   return make_number (np);
  933. }
  934.  
  935. /* Search for the n'th occurrence of STRING in the current buffer,
  936.    starting at position POS and stopping at position LIM,
  937.    treating PAT as a literal string if RE is false or as
  938.    a regular expression if RE is true.
  939.  
  940.    If N is positive, searching is forward and LIM must be greater than POS.
  941.    If N is negative, searching is backward and LIM must be less than POS.
  942.  
  943.    Returns -x if only N-x occurrences found (x > 0),
  944.    or else the position at the beginning of the Nth occurrence
  945.    (if searching backward) or the end (if searching forward).  */
  946.  
  947. static Bytind
  948. search_buffer (Lisp_Object string, Bytind pos, Bytind lim, int n, int RE,
  949.            unsigned char *trt, unsigned char *inverse_trt)
  950. {
  951.   /* !!#### This function has not been Mule-ized */
  952.   Bytecount len = 0;
  953.   Bufbyte *base_pat = 0;
  954.   int *BM_tab;
  955.   int *BM_tab_base;
  956.   int direction = ((n > 0) ? 1 : -1);
  957.   int dirlen;
  958.   int infinity, limit, k, stride_for_teases = 0;
  959.   Bufbyte *pat = 0;
  960.   Bufbyte *cursor, *p_limit, *ptr2;  
  961.   int i, j;
  962.   Bytind p1, p2;
  963.   Bytecount s1, s2;
  964.   struct buffer *buf = current_buffer;
  965.  
  966.   if (!RE)
  967.     {
  968.       CHECK_STRING (string, 0);
  969.       base_pat = string_data (XSTRING (string));
  970.       len = string_length (XSTRING (string));
  971.  
  972.       /* Null string is found at starting position.  */
  973.       if (len == 0)
  974.     {
  975.       set_search_regs (pos, 0);
  976.       return pos;
  977.     }
  978.     }
  979.   else                    /* type check of string also done. */
  980.     compile_pattern (string, &searchbuf, &search_regs,
  981.              (char *) trt, direction < 0, 0);
  982.  
  983.   /* Searching 0 times means don't move.  */
  984.   if (n == 0)
  985.     return pos;
  986.  
  987.   if (RE            /* Here we detect whether the */
  988.                 /* generality of an RE search is */
  989.                 /* really needed. */
  990.       /* first item is "exact match" */
  991. #ifdef EMACS19_REGEXP
  992.       && *(searchbuf.buffer) == (char) RE_EXACTN_VALUE
  993. #else
  994.       && *(searchbuf.buffer) == exactn
  995. #endif
  996.       && searchbuf.buffer[1] + 2 == searchbuf.used) /*first is ONLY item */
  997.     {
  998.       RE = 0;            /* can do straight (non RE) search */
  999.       pat = (base_pat = (unsigned char *) searchbuf.buffer + 2);
  1000.                 /* trt already applied */
  1001.       len = searchbuf.used - 2;
  1002.     }
  1003.   else if (!RE)
  1004.     {
  1005.       pat = (Bufbyte *) alloca (len * sizeof (Bufbyte));
  1006.  
  1007.       for (i = len; i--;)        /* Copy the pattern; apply trt */
  1008.     *pat++ = (((int) trt) ? trt [*base_pat++] : *base_pat++);
  1009.       pat -= len; base_pat = pat;
  1010.     }
  1011.  
  1012.   if (RE)
  1013.     {
  1014.       /* Get pointers and sizes of the two strings
  1015.      that make up the visible portion of the buffer. */
  1016.  
  1017.       p1 = BI_BUF_BEGV (buf);
  1018.       p2 = BI_BUF_CEILING_OF (buf, p1);
  1019.       s1 = p2 - p1;
  1020.       s2 = BI_BUF_ZV (buf) - p2;
  1021.   
  1022.       while (n < 0)
  1023.     {
  1024.           int val;
  1025.       QUIT;
  1026.       val = re_search_2 (&searchbuf,
  1027.                  (char *) BI_BUF_BYTE_ADDRESS (buf, p1), s1,
  1028.                  (char *) BI_BUF_BYTE_ADDRESS (buf, p2), s2,
  1029.                              pos - BI_BUF_BEGV (buf), lim - pos, &search_regs,
  1030.                              /* Don't allow match past current point */
  1031.                  /* mstop for backward search is */
  1032.                  /* BEGV - BEGV */
  1033.                  (EXTENDED_REGEXP_P (&searchbuf) ? 0 :
  1034.                   pos - BI_BUF_BEGV (buf))
  1035.         );
  1036.       if (val == -2)
  1037.         matcher_overflow ();
  1038.       if (val >= 0)
  1039.         {
  1040.           j = BI_BUF_BEGV (buf);
  1041.           for (i = 0; i < SEARCH_NREGS (&search_regs); i++)
  1042.         if (search_regs.start[i] >= 0)
  1043.           {
  1044.             search_regs.start[i] += j;
  1045.             search_regs.end[i] += j;
  1046.           }
  1047.           XSETBUFFER (last_thing_searched, buf);
  1048.           /* Set pos to the new position. */
  1049.           pos = search_regs.start[0];
  1050.         }
  1051.       else
  1052.         {
  1053.           return (n);
  1054.         }
  1055.       n++;
  1056.     }
  1057.       while (n > 0)
  1058.     {
  1059.       int val;
  1060.       QUIT;
  1061.           val = re_search_2 (&searchbuf,
  1062.                  (char *) BI_BUF_BYTE_ADDRESS (buf, p1), s1,
  1063.                  (char *) BI_BUF_BYTE_ADDRESS (buf, p2), s2,
  1064.                              pos - BI_BUF_BEGV (buf), lim - pos, &search_regs,
  1065.                              lim - BI_BUF_BEGV (buf));
  1066.       if (val == -2)
  1067.         matcher_overflow ();
  1068.       if (val >= 0)
  1069.         {
  1070.           j = BI_BUF_BEGV (buf);
  1071.           for (i = 0; i < SEARCH_NREGS (&search_regs); i++)
  1072.         if (search_regs.start[i] >= 0)
  1073.           {
  1074.             search_regs.start[i] += j;
  1075.             search_regs.end[i] += j;
  1076.           }
  1077.           XSETBUFFER (last_thing_searched, buf);
  1078.           pos = search_regs.end[0];
  1079.         }
  1080.       else
  1081.         {
  1082.           return (0 - n);
  1083.         }
  1084.       n--;
  1085.     }
  1086.       return (pos);
  1087.     }
  1088.   else                /* non-RE case */
  1089.     {
  1090. #ifdef C_ALLOCA
  1091.       int BM_tab_space[0400];
  1092.       BM_tab = &BM_tab_space[0];
  1093. #else
  1094.       BM_tab = (int *) alloca (0400 * sizeof (int));
  1095. #endif
  1096.       /* The general approach is that we are going to maintain that we know */
  1097.       /* the first (closest to the present position, in whatever direction */
  1098.       /* we're searching) character that could possibly be the last */
  1099.       /* (furthest from present position) character of a valid match.  We */
  1100.       /* advance the state of our knowledge by looking at that character */
  1101.       /* and seeing whether it indeed matches the last character of the */
  1102.       /* pattern.  If it does, we take a closer look.  If it does not, we */
  1103.       /* move our pointer (to putative last characters) as far as is */
  1104.       /* logically possible.  This amount of movement, which I call a */
  1105.       /* stride, will be the length of the pattern if the actual character */
  1106.       /* appears nowhere in the pattern, otherwise it will be the distance */
  1107.       /* from the last occurrence of that character to the end of the */
  1108.       /* pattern. */
  1109.       /* As a coding trick, an enormous stride is coded into the table for */
  1110.       /* characters that match the last character.  This allows use of only */
  1111.       /* a single test, a test for having gone past the end of the */
  1112.       /* permissible match region, to test for both possible matches (when */
  1113.       /* the stride goes past the end immediately) and failure to */
  1114.       /* match (where you get nudged past the end one stride at a time). */ 
  1115.  
  1116.       /* Here we make a "mickey mouse" BM table.  The stride of the search */
  1117.       /* is determined only by the last character of the putative match. */
  1118.       /* If that character does not match, we will stride the proper */
  1119.       /* distance to propose a match that superimposes it on the last */
  1120.       /* instance of a character that matches it (per trt), or misses */
  1121.       /* it entirely if there is none. */  
  1122.  
  1123.       dirlen = len * direction;
  1124.       infinity = dirlen - (lim + pos + len + len) * direction;
  1125.       if (direction < 0)
  1126.     pat = (base_pat += len - 1);
  1127.       BM_tab_base = BM_tab;
  1128.       BM_tab += 0400;
  1129.       j = dirlen;        /* to get it in a register */
  1130.       /* A character that does not appear in the pattern induces a */
  1131.       /* stride equal to the pattern length. */
  1132.       while (BM_tab_base != BM_tab)
  1133.     {
  1134.       *--BM_tab = j;
  1135.       *--BM_tab = j;
  1136.       *--BM_tab = j;
  1137.       *--BM_tab = j;
  1138.     }
  1139.       i = 0;
  1140.       while (i != infinity)
  1141.     {
  1142.       j = pat[i]; i += direction;
  1143.       if (i == dirlen) i = infinity;
  1144.       if ((int) trt)
  1145.         {
  1146.           k = (j = trt[j]);
  1147.           if (i == infinity)
  1148.         stride_for_teases = BM_tab[j];
  1149.           BM_tab[j] = dirlen - i;
  1150.           /* A translation table is accompanied by its inverse -- see */
  1151.           /* comment following downcase_table for details */ 
  1152.  
  1153.           while ((j = inverse_trt[j]) != k)
  1154.         BM_tab[j] = dirlen - i;
  1155.         }
  1156.       else
  1157.         {
  1158.           if (i == infinity)
  1159.         stride_for_teases = BM_tab[j];
  1160.           BM_tab[j] = dirlen - i;
  1161.         }
  1162.       /* stride_for_teases tells how much to stride if we get a */
  1163.       /* match on the far character but are subsequently */
  1164.       /* disappointed, by recording what the stride would have been */
  1165.       /* for that character if the last character had been */
  1166.       /* different. */
  1167.     }
  1168.       infinity = dirlen - infinity;
  1169.       pos += dirlen - ((direction > 0) ? direction : 0);
  1170.       /* loop invariant - pos points at where last char (first char if reverse)
  1171.      of pattern would align in a possible match.  */
  1172.       while (n != 0)
  1173.     {
  1174.       if ((lim - pos - (direction > 0)) * direction < 0)
  1175.         return (n * (0 - direction));
  1176.       /* First we do the part we can by pointers (maybe nothing) */
  1177.       QUIT;
  1178.       pat = base_pat;
  1179.       limit = pos - dirlen + direction;
  1180.       /* XEmacs change: definitions of CEILING_OF and FLOOR_OF
  1181.          have changed.  See buffer.h. */
  1182.       limit = ((direction > 0)
  1183.            ? BI_BUF_CEILING_OF (buf, limit) - 1
  1184.            : BI_BUF_FLOOR_OF (buf, limit + 1));
  1185.       /* LIMIT is now the last (not beyond-last!) value
  1186.          POS can take on without hitting edge of buffer or the gap.  */
  1187.       limit = ((direction > 0)
  1188.            ? min (lim - 1, min (limit, pos + 20000))
  1189.            : max (lim, max (limit, pos - 20000)));
  1190.       if ((limit - pos) * direction > 20)
  1191.         {
  1192.           p_limit = BI_BUF_BYTE_ADDRESS (buf, limit);
  1193.           ptr2 = (cursor = BI_BUF_BYTE_ADDRESS (buf, pos));
  1194.           /* In this loop, pos + cursor - ptr2 is the surrogate for pos */
  1195.           while (1)        /* use one cursor setting as long as i can */
  1196.         {
  1197.           if (direction > 0) /* worth duplicating */
  1198.             {
  1199.               /* Use signed comparison if appropriate
  1200.              to make cursor+infinity sure to be > p_limit.
  1201.              Assuming that the buffer lies in a range of addresses
  1202.              that are all "positive" (as ints) or all "negative",
  1203.              either kind of comparison will work as long
  1204.              as we don't step by infinity.  So pick the kind
  1205.              that works when we do step by infinity.  */
  1206.               if ((int) (p_limit + infinity) > (int) p_limit)
  1207.             while ((int) cursor <= (int) p_limit)
  1208.               cursor += BM_tab[*cursor];
  1209.               else
  1210.             while ((unsigned int) cursor <= (unsigned int) p_limit)
  1211.               cursor += BM_tab[*cursor];
  1212.             }
  1213.           else
  1214.             {
  1215.               if ((int) (p_limit + infinity) < (int) p_limit)
  1216.             while ((int) cursor >= (int) p_limit)
  1217.               cursor += BM_tab[*cursor];
  1218.               else
  1219.             while ((unsigned int) cursor >= (unsigned int) p_limit)
  1220.               cursor += BM_tab[*cursor];
  1221.             }
  1222. /* If you are here, cursor is beyond the end of the searched region. */
  1223.  /* This can happen if you match on the far character of the pattern, */
  1224.  /* because the "stride" of that character is infinity, a number able */
  1225.  /* to throw you well beyond the end of the search.  It can also */
  1226.  /* happen if you fail to match within the permitted region and would */
  1227.  /* otherwise try a character beyond that region */
  1228.           if ((cursor - p_limit) * direction <= len)
  1229.             break;    /* a small overrun is genuine */
  1230.           cursor -= infinity; /* large overrun = hit */
  1231.           i = dirlen - direction;
  1232.           if ((int) trt)
  1233.             {
  1234.               while ((i -= direction) + direction != 0)
  1235.             if (pat[i] != trt[*(cursor -= direction)])
  1236.               break;
  1237.             }
  1238.           else
  1239.             {
  1240.               while ((i -= direction) + direction != 0)
  1241.             if (pat[i] != *(cursor -= direction))
  1242.               break;
  1243.             }
  1244.           cursor += dirlen - i - direction;    /* fix cursor */
  1245.           if (i + direction == 0)
  1246.             {
  1247.               cursor -= direction;
  1248.  
  1249.                       set_search_regs (pos + cursor - ptr2 + ((direction > 0)
  1250.                                 ? 1 - len : 0),
  1251.                        len);
  1252.  
  1253.               if ((n -= direction) != 0)
  1254.             cursor += dirlen; /* to resume search */
  1255.               else
  1256.             return ((direction > 0)
  1257.                 ? search_regs.end[0] : search_regs.start[0]);
  1258.             }
  1259.           else
  1260.             cursor += stride_for_teases; /* <sigh> we lose -  */
  1261.         }
  1262.           pos += cursor - ptr2;
  1263.         }
  1264.       else
  1265.         /* Now we'll pick up a clump that has to be done the hard */
  1266.         /* way because it covers a discontinuity */
  1267.         {
  1268.           /* XEmacs change: definitions of CEILING_OF and FLOOR_OF
  1269.          have changed.  See buffer.h. */
  1270.           limit = ((direction > 0)
  1271.                ? BI_BUF_CEILING_OF (buf, pos - dirlen + 1) - 1
  1272.                : BI_BUF_FLOOR_OF (buf, pos - dirlen));
  1273.           limit = ((direction > 0)
  1274.                ? min (limit + len, lim - 1)
  1275.                : max (limit - len, lim));
  1276.           /* LIMIT is now the last value POS can have
  1277.          and still be valid for a possible match.  */
  1278.           while (1)
  1279.         {
  1280.           /* This loop can be coded for space rather than */
  1281.           /* speed because it will usually run only once. */
  1282.           /* (the reach is at most len + 21, and typically */
  1283.           /* does not exceed len) */    
  1284.           while ((limit - pos) * direction >= 0)
  1285.             pos += BM_tab[BI_BUF_FETCH_CHAR (buf, pos)];
  1286.           /* now run the same tests to distinguish going off the */
  1287.           /* end, a match or a phony match. */
  1288.           if ((pos - limit) * direction <= len)
  1289.             break;    /* ran off the end */
  1290.           /* Found what might be a match.
  1291.              Set POS back to last (first if reverse) char pos.  */
  1292.           pos -= infinity;
  1293.           i = dirlen - direction;
  1294.           while ((i -= direction) + direction != 0)
  1295.             {
  1296.               pos -= direction;
  1297.               if (pat[i] != (((int) trt)
  1298.                      ? trt[BI_BUF_FETCH_CHAR (buf, pos)]
  1299.                      : BI_BUF_FETCH_CHAR (buf, pos)))
  1300.             break;
  1301.             }
  1302.           /* Above loop has moved POS part or all the way
  1303.              back to the first char pos (last char pos if reverse).
  1304.              Set it once again at the last (first if reverse) char.  */
  1305.           pos += dirlen - i- direction;
  1306.           if (i + direction == 0)
  1307.             {
  1308.               pos -= direction;
  1309.  
  1310.               set_search_regs (pos + ((direction > 0) ? 1 - len : 0),
  1311.                        len);
  1312.  
  1313.               if ((n -= direction) != 0)
  1314.             pos += dirlen; /* to resume search */
  1315.               else
  1316.             return ((direction > 0)
  1317.                 ? search_regs.end[0] : search_regs.start[0]);
  1318.             }
  1319.           else
  1320.             pos += stride_for_teases;
  1321.         }
  1322.           }
  1323.       /* We have done one clump.  Can we continue? */
  1324.       if ((lim - pos) * direction < 0)
  1325.         return ((0 - n) * direction);
  1326.     }
  1327.       return pos;
  1328.     }
  1329. }
  1330.  
  1331. /* Record beginning BEG and end BEG + LEN
  1332.    for a match just found in the current buffer.  */
  1333.  
  1334. static void
  1335. set_search_regs (int beg, int len)
  1336. {
  1337.   /* !!#### This function has not been Mule-ized */
  1338. #ifdef EMACS19_REGEXP
  1339.   /* Make sure we have registers in which to store
  1340.      the match position.  */
  1341.   if (search_regs.num_regs == 0)
  1342.   {
  1343.     regoff_t *starts, *ends;
  1344.  
  1345.     starts = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
  1346.     ends = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
  1347.     re_set_registers (&searchbuf,
  1348.                       &search_regs,
  1349.                       2, starts, ends);
  1350.   }
  1351. #endif /* EMACS19_REGEXP */
  1352.  
  1353.   search_regs.start[0] = beg;
  1354.   search_regs.end[0] = beg + len;
  1355.   XSETBUFFER (last_thing_searched, current_buffer);
  1356. }
  1357.  
  1358.  
  1359. /* Given a string of words separated by word delimiters,
  1360.   compute a regexp that matches those exact words
  1361.   separated by arbitrary punctuation.  */
  1362.  
  1363. static Lisp_Object
  1364. wordify (Lisp_Object string)
  1365. {
  1366.   /* !!#### This function has not been Mule-ized */
  1367.   unsigned char *p, *o;
  1368.   int i, len, punct_count = 0, word_count = 0;
  1369.   Lisp_Object val;
  1370.   Lisp_Object syntax_table = current_buffer->syntax_table;
  1371.  
  1372.   CHECK_STRING (string, 0);
  1373.   p = string_data (XSTRING (string));
  1374.   len = string_length (XSTRING (string));
  1375.  
  1376.   for (i = 0; i < len; i++)
  1377.     if (SYNTAX (syntax_table, p[i]) != Sword)
  1378.       {
  1379.     punct_count++;
  1380.     if (i > 0 && SYNTAX (syntax_table, p[i-1]) == Sword)
  1381.           word_count++;
  1382.       }
  1383.   if (SYNTAX (syntax_table, p[len-1]) == Sword)
  1384.     word_count++;
  1385.   if (!word_count) return build_string ("");
  1386.  
  1387.   val = make_string (p,
  1388.              len - punct_count + 5 * (word_count - 1) + 4);
  1389.  
  1390.   o = string_data (XSTRING (val));
  1391.   *o++ = '\\';
  1392.   *o++ = 'b';
  1393.  
  1394.   for (i = 0; i < len; i++)
  1395.     if (SYNTAX (syntax_table, p[i]) == Sword)
  1396.       *o++ = p[i];
  1397.     else if (i > 0
  1398.              && SYNTAX (syntax_table, p[i-1]) == Sword
  1399.              && --word_count)
  1400.       {
  1401.     *o++ = '\\';
  1402.     *o++ = 'W';
  1403.     *o++ = '\\';
  1404.     *o++ = 'W';
  1405.     *o++ = '*';
  1406.       }
  1407.  
  1408.   *o++ = '\\';
  1409.   *o++ = 'b';
  1410.  
  1411.   return val;
  1412. }
  1413.  
  1414. DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
  1415.   "sSearch backward: ",
  1416.   "Search backward from point for STRING.\n\
  1417. Set point to the beginning of the occurrence found, and return point.\n\
  1418. An optional second argument bounds the search; it is a buffer position.\n\
  1419. The match found must not extend before that position.\n\
  1420. Optional third argument, if t, means if fail just return nil (no error).\n\
  1421.  If not nil and not t, position at limit of search and return nil.\n\
  1422. Optional fourth argument is repeat count--search for successive occurrences.\n\
  1423. See also the functions `match-beginning', `match-end' and `replace-match'.")
  1424.   (string, bound, no_error, count)
  1425.      Lisp_Object string, bound, no_error, count;
  1426. {
  1427.   return search_command (string, bound, no_error, count, -1, 0);
  1428. }
  1429.  
  1430. DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "sSearch: ",
  1431.   "Search forward from point for STRING.\n\
  1432. Set point to the end of the occurrence found, and return point.\n\
  1433. An optional second argument bounds the search; it is a buffer position.\n\
  1434. The match found must not extend after that position.  nil is equivalent\n\
  1435.   to (point-max).\n\
  1436. Optional third argument, if t, means if fail just return nil (no error).\n\
  1437.   If not nil and not t, move to limit of search and return nil.\n\
  1438. Optional fourth argument is repeat count--search for successive occurrences.\n\
  1439. See also the functions `match-beginning', `match-end' and `replace-match'.")
  1440.   (string, bound, no_error, count)
  1441.      Lisp_Object string, bound, no_error, count;
  1442. {
  1443.   return search_command (string, bound, no_error, count, 1, 0);
  1444. }
  1445.  
  1446. DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
  1447.   "sWord search backward: ",
  1448.   "Search backward from point for STRING, ignoring differences in punctuation.\n\
  1449. Set point to the beginning of the occurrence found, and return point.\n\
  1450. An optional second argument bounds the search; it is a buffer position.\n\
  1451. The match found must not extend before that position.\n\
  1452. Optional third argument, if t, means if fail just return nil (no error).\n\
  1453.   If not nil and not t, move to limit of search and return nil.\n\
  1454. Optional fourth argument is repeat count--search for successive occurrences.")
  1455.   (string, bound, no_error, count)
  1456.      Lisp_Object string, bound, no_error, count;
  1457. {
  1458.   return search_command (wordify (string), bound, no_error, count, -1, 1);
  1459. }
  1460.  
  1461. DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
  1462.   "sWord search: ",
  1463.   "Search forward from point for STRING, ignoring differences in punctuation.\n\
  1464. Set point to the end of the occurrence found, and return point.\n\
  1465. An optional second argument bounds the search; it is a buffer position.\n\
  1466. The match found must not extend after that position.\n\
  1467. Optional third argument, if t, means if fail just return nil (no error).\n\
  1468.   If not nil and not t, move to limit of search and return nil.\n\
  1469. Optional fourth argument is repeat count--search for successive occurrences.")
  1470.   (string, bound, no_error, count)
  1471.      Lisp_Object string, bound, no_error, count;
  1472. {
  1473.   return search_command (wordify (string), bound, no_error, count, 1, 1);
  1474. }
  1475.  
  1476. DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
  1477.   "sRE search backward: ",
  1478.   "Search backward from point for match for regular expression REGEXP.\n\
  1479. Set point to the beginning of the match, and return point.\n\
  1480. The match found is the one starting last in the buffer\n\
  1481. and yet ending before the origin of the search.\n\
  1482. An optional second argument bounds the search; it is a buffer position.\n\
  1483. The match found must start at or after that position.\n\
  1484. Optional third argument, if t, means if fail just return nil (no error).\n\
  1485.   If not nil and not t, move to limit of search and return nil.\n\
  1486. Optional fourth argument is repeat count--search for successive occurrences.\n\
  1487. See also the functions `match-beginning', `match-end' and `replace-match'.")
  1488.   (regexp, bound, no_error, count)
  1489.      Lisp_Object regexp, bound, no_error, count;
  1490. {
  1491.   return search_command (regexp, bound, no_error, count, -1, 1);
  1492. }
  1493.  
  1494. DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
  1495.   "sRE search: ",
  1496.   "Search forward from point for regular expression REGEXP.\n\
  1497. Set point to the end of the occurrence found, and return point.\n\
  1498. An optional second argument bounds the search; it is a buffer position.\n\
  1499. The match found must not extend after that position.\n\
  1500. Optional third argument, if t, means if fail just return nil (no error).\n\
  1501.   If not nil and not t, move to limit of search and return nil.\n\
  1502. Optional fourth argument is repeat count--search for successive occurrences.\n\
  1503. See also the functions `match-beginning', `match-end' and `replace-match'.")
  1504.   (regexp, bound, no_error, count)
  1505.      Lisp_Object regexp, bound, no_error, count;
  1506. {
  1507.   return search_command (regexp, bound, no_error, count, 1, 1);
  1508. }
  1509.  
  1510.  
  1511. DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 3, 0,
  1512.   "Replace text matched by last search with NEWTEXT.\n\
  1513. If second arg FIXEDCASE is non-nil, do not alter case of replacement text.\n\
  1514. Otherwise maybe capitalize the whole text, or maybe just word initials,\n\
  1515. based on the replaced text.\n\
  1516. If the replaced text has only capital letters\n\
  1517. and has at least one multiletter word, convert NEWTEXT to all caps.\n\
  1518. If the replaced text has at least one word starting with a capital letter,\n\
  1519. then capitalize each word in NEWTEXT.\n\n\
  1520. If third arg LITERAL is non-nil, insert NEWTEXT literally.\n\
  1521. Otherwise treat `\\' as special:\n\
  1522.   `\\&' in NEWTEXT means substitute original matched text.\n\
  1523.   `\\N' means substitute what matched the Nth `\\(...\\)'.\n\
  1524.        If Nth parens didn't match, substitute nothing.\n\
  1525.   `\\\\' means insert one `\\'.\n\
  1526.   `\\u' means upcase the next character.\n\
  1527.   `\\l' means downcase the next character.\n\
  1528.   `\\U' means begin upcasing all following characters.\n\
  1529.   `\\L' means begin downcasing all following characters.\n\
  1530.   `\\E' means terminate the effect of any `\\U' or `\\L'.\n\
  1531.   Case changes made with `\\u', `\\l', `\\U', and `\\L' override\n\
  1532.   all other case changes that may be made in the replaced text.\n\
  1533. FIXEDCASE and LITERAL are optional arguments.\n\
  1534. Leaves point at end of replacement text.")
  1535.   (newtext, fixedcase, literal)
  1536.      Lisp_Object newtext, fixedcase, literal;
  1537. {
  1538.   /* This function can GC */
  1539.   enum { nochange, all_caps, cap_initial } case_action;
  1540.   Bufpos pos, last;
  1541.   int some_multiletter_word;
  1542.   int some_lowercase;
  1543.   int some_uppercase;
  1544.   int some_nonuppercase_initial;
  1545.   Emchar c, prevc;
  1546.   int inslen;
  1547.   struct buffer *buf = current_buffer;
  1548.   Lisp_Object syntax_table = buf->syntax_table;
  1549.   int mc_count;
  1550.   Lisp_Object buffer;
  1551.   int_dynarr *ul_action_dynarr = 0;
  1552.   int_dynarr *ul_pos_dynarr = 0;
  1553.  
  1554.   XSETBUFFER (buffer, buf);
  1555.   CHECK_STRING (newtext, 0);
  1556.  
  1557.   case_action = nochange;    /* We tried an initialization */
  1558.                 /* but some C compilers blew it */
  1559.  
  1560. #ifdef EMACS19_REGEXP
  1561.   if (search_regs.num_regs <= 0)
  1562.     error ("replace-match called before any match found");
  1563. #endif
  1564.  
  1565.   if (search_regs.start[0] < BUF_BEGV (buf)
  1566.       || search_regs.start[0] > search_regs.end[0]
  1567.       || search_regs.end[0] > BUF_ZV (buf))
  1568.     args_out_of_range (make_number (search_regs.start[0]),
  1569.                make_number (search_regs.end[0]));
  1570.  
  1571.   if (NILP (fixedcase))
  1572.     {
  1573.       /* Decide how to casify by examining the matched text. */
  1574.  
  1575.       last = search_regs.end[0];
  1576.       prevc = '\n';
  1577.       case_action = all_caps;
  1578.  
  1579.       /* some_multiletter_word is set nonzero if any original word
  1580.      is more than one letter long. */
  1581.       some_multiletter_word = 0;
  1582.       some_lowercase = 0;
  1583.       some_nonuppercase_initial = 0;
  1584.       some_uppercase = 0;
  1585.  
  1586.       for (pos = search_regs.start[0]; pos < last; pos++)
  1587.     {
  1588.       c = BUF_FETCH_CHAR (buf, pos);
  1589.       if (LOWERCASEP (buf, c))
  1590.         {
  1591.           /* Cannot be all caps if any original char is lower case */
  1592.  
  1593.           some_lowercase = 1;
  1594.           if (SYNTAX (syntax_table, prevc) != Sword)
  1595.         some_nonuppercase_initial = 1;
  1596.           else
  1597.         some_multiletter_word = 1;
  1598.         }
  1599.       else if (!NOCASEP (buf, c))
  1600.         {
  1601.           some_uppercase = 1;
  1602.           if (SYNTAX (syntax_table, prevc) != Sword)
  1603.         ;
  1604.           else
  1605.         some_multiletter_word = 1;
  1606.         }
  1607.       else
  1608.         {
  1609.           /* If the initial is a caseless word constituent,
  1610.          treat that like a lowercase initial.  */
  1611.           if (SYNTAX (syntax_table, prevc) != Sword)
  1612.         some_nonuppercase_initial = 1;
  1613.         }
  1614.  
  1615.       prevc = c;
  1616.     }
  1617.  
  1618.       /* Convert to all caps if the old text is all caps
  1619.      and has at least one multiletter word.  */
  1620.       if (! some_lowercase && some_multiletter_word)
  1621.     case_action = all_caps;
  1622.       /* Capitalize each word, if the old text has all capitalized words.  */
  1623.       else if (!some_nonuppercase_initial && some_multiletter_word)
  1624.     case_action = cap_initial;
  1625.       else if (!some_nonuppercase_initial && some_uppercase)
  1626.     /* Should x -> yz, operating on X, give Yz or YZ?
  1627.        We'll assume the latter.  */
  1628.     case_action = all_caps;
  1629.       else
  1630.     case_action = nochange;
  1631.     }
  1632.  
  1633.   mc_count = begin_multiple_change (buf, search_regs.start[0],
  1634.                     search_regs.end[0]);
  1635.  
  1636.   /* We insert the replacement text before the old text, and then
  1637.      delete the original text.  This means that markers at the
  1638.      beginning or end of the original will float to the corresponding
  1639.      position in the replacement.  */
  1640.   BUF_SET_PT (buf, search_regs.start[0]);
  1641.   if (!NILP (literal))
  1642.     Finsert (1, &newtext);
  1643.   else
  1644.     {
  1645.       Charcount stlen = string_char_length (XSTRING (newtext));
  1646.       Charcount strpos;
  1647.       struct gcpro gcpro1;
  1648.       GCPRO1 (newtext);
  1649.       for (strpos = 0; strpos < stlen; strpos++)
  1650.     {
  1651.       int offset = BUF_PT (buf) - search_regs.start[0];
  1652.  
  1653.       c = string_char (XSTRING (newtext), strpos);
  1654.       if (c == '\\')
  1655.         {
  1656.           c = string_char (XSTRING (newtext), ++strpos);
  1657.           if (c == '&')
  1658.         Finsert_buffer_substring 
  1659.                   (buffer,
  1660.                    make_number (search_regs.start[0] + offset),
  1661.                    make_number (search_regs.end[0] + offset));
  1662.           else if (c >= '1' && c <= '9' &&
  1663.                c <= SEARCH_NREGS (&search_regs) + '0')
  1664.         {
  1665.           if (search_regs.start[c - '0'] >= 1)
  1666.             Finsert_buffer_substring
  1667.                       (buffer,
  1668.                        make_number (search_regs.start[c - '0'] + offset),
  1669.                        make_number (search_regs.end[c - '0'] + offset));
  1670.         }
  1671.           else if (c == 'U' || c == 'u' || c == 'L' || c == 'l' ||
  1672.                c == 'E')
  1673.         {
  1674.           /* Keep track of all case changes requested, but don't
  1675.              make them now.  Do them later so we override
  1676.              everything else. */
  1677.           if (!ul_pos_dynarr)
  1678.             {
  1679.               ul_pos_dynarr = Dynarr_new (int);
  1680.               ul_action_dynarr = Dynarr_new (int);
  1681.             }
  1682.           Dynarr_add (ul_pos_dynarr, BUF_PT (buf));
  1683.           Dynarr_add (ul_action_dynarr, c);
  1684.         }
  1685.           else
  1686.         buffer_insert_emacs_char (buf, c);
  1687.         }
  1688.       else
  1689.         buffer_insert_emacs_char (buf, c);
  1690.     }
  1691.       UNGCPRO;
  1692.     }
  1693.  
  1694.   inslen = BUF_PT (buf) - (search_regs.start[0]);
  1695.   buffer_delete_range (buf, search_regs.start[0] + inslen, search_regs.end[0] +
  1696.                inslen, 0);
  1697.  
  1698.   if (case_action == all_caps)
  1699.     Fupcase_region (make_number (BUF_PT (buf) - inslen),
  1700.             make_number (BUF_PT (buf)),  buffer);
  1701.   else if (case_action == cap_initial)
  1702.     upcase_initials_region (buf, make_number (BUF_PT (buf) - inslen),
  1703.                             make_number (BUF_PT (buf)));
  1704.  
  1705.   /* Now go through and make all the case changes that were requested
  1706.      in the replacement string. */
  1707.   if (ul_pos_dynarr)
  1708.     {
  1709.       Bufpos eend = BUF_PT (buf);
  1710.       int i = 0;
  1711.       int cur_action = 'E';
  1712.  
  1713.       for (pos = BUF_PT (buf) - inslen; pos < eend; pos++)
  1714.     {
  1715.       Emchar curchar = BUF_FETCH_CHAR (buf, pos);
  1716.       Emchar newchar = -1;
  1717.       if (i < Dynarr_length (ul_pos_dynarr) &&
  1718.           pos == Dynarr_at (ul_pos_dynarr, i))
  1719.         {
  1720.           int new_action = Dynarr_at (ul_action_dynarr, i);
  1721.           i++;
  1722.           if (new_action == 'u')
  1723.         newchar = UPCASE (buf, curchar);
  1724.           else if (new_action == 'l')
  1725.         newchar = DOWNCASE (buf, curchar);
  1726.           else
  1727.         cur_action = new_action;
  1728.         }
  1729.       if (newchar == -1)
  1730.         {
  1731.           if (cur_action == 'U')
  1732.         newchar = UPCASE (buf, curchar);
  1733.           else if (cur_action == 'L')
  1734.         newchar = DOWNCASE (buf, curchar);
  1735.           else
  1736.         newchar = curchar;
  1737.         }
  1738.       if (newchar != curchar)
  1739.         buffer_replace_char (buf, pos, newchar, 0, 0);
  1740.     }
  1741.  
  1742.       /* #### will not be freed if an after-change function throws,
  1743.      or whatever */
  1744.       Dynarr_free (ul_action_dynarr);
  1745.       Dynarr_free (ul_pos_dynarr);
  1746.     }
  1747.  
  1748.   end_multiple_change (buf, mc_count);
  1749.  
  1750.   return Qnil;
  1751. }
  1752.  
  1753. static Lisp_Object
  1754. match_limit (Lisp_Object num, int beginningp)
  1755. {
  1756.   /* !!#### This function has not been Mule-ized */
  1757.   int n;
  1758.  
  1759.   CHECK_INT (num, 0);
  1760.   n = XINT (num);
  1761.   if (n < 0 || n >= SEARCH_NREGS (&search_regs))
  1762.     args_out_of_range (num, make_number (SEARCH_NREGS (&search_regs)));
  1763. #ifdef EMACS19_REGEXP
  1764.   if (search_regs.num_regs <= 0)
  1765.     return (Qnil);
  1766. #endif
  1767.   if (search_regs.start[n] < 0)
  1768.     return Qnil;
  1769.   return (make_number ((beginningp) ? search_regs.start[n]
  1770.                             : search_regs.end[n]));
  1771. }
  1772.  
  1773. DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
  1774.   "Return position of start of text matched by last regexp search.\n\
  1775. NUM, specifies which parenthesized expression in the last regexp.\n\
  1776.  Value is nil if NUMth pair didn't match, or there were less than NUM pairs.\n\
  1777. Zero means the entire text matched by the whole regexp or whole string.")
  1778.   (num)
  1779.      Lisp_Object num;
  1780. {
  1781.   return match_limit (num, 1);
  1782. }
  1783.  
  1784. DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
  1785.   "Return position of end of text matched by last regexp search.\n\
  1786. NUM specifies which parenthesized expression in the last regexp.\n\
  1787.  Value is nil if NUMth pair didn't match, or there were less than NUM pairs.\n\
  1788. Zero means the entire text matched by the whole regexp or whole string.")
  1789.   (num)
  1790.      Lisp_Object num;
  1791. {
  1792.   return match_limit (num, 0);
  1793.  
  1794. DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 0, 0,
  1795.   "Return a list containing all info on what the last regexp search matched.\n\
  1796. Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.\n\
  1797. All the elements are markers or nil (nil if the Nth pair didn't match)\n\
  1798. if the last match was on a buffer; integers or nil if a string was matched.\n\
  1799. Use `store-match-data' to reinstate the data in this list.")
  1800.   ()
  1801. {
  1802.   /* !!#### This function has not been Mule-ized */
  1803.   Lisp_Object *data;
  1804.   int i, len;
  1805.  
  1806.   if (NILP (last_thing_searched))
  1807.     error ("match-data called before any match found");
  1808.  
  1809.   data = (Lisp_Object *) alloca ((2 * SEARCH_NREGS (&search_regs))
  1810.                  * sizeof (Lisp_Object));
  1811.  
  1812.   len = -1;
  1813.   for (i = 0; i < SEARCH_NREGS (&search_regs); i++)
  1814.     {
  1815.       int start = search_regs.start[i];
  1816.       if (start >= 0)
  1817.     {
  1818.       if (EQ (last_thing_searched, Qt))
  1819.         {
  1820.           data[2 * i] = make_number (start);
  1821.           data[2 * i + 1] = make_number (search_regs.end[i]);
  1822.         }
  1823.       else if (BUFFERP (last_thing_searched))
  1824.         {
  1825.           data[2 * i] = Fmake_marker ();
  1826.           Fset_marker (data[2 * i],
  1827.                make_number (start),
  1828.                last_thing_searched);
  1829.           data[2 * i + 1] = Fmake_marker ();
  1830.           Fset_marker (data[2 * i + 1],
  1831.                make_number (search_regs.end[i]), 
  1832.                last_thing_searched);
  1833.         }
  1834.       else
  1835.         /* last_thing_searched must always be Qt, a buffer, or Qnil.  */
  1836.         abort ();
  1837.  
  1838.       len = i;
  1839.     }
  1840.       else
  1841.     data[2 * i] = data [2 * i + 1] = Qnil;
  1842.     }
  1843.   return Flist (2 * len + 2, data);
  1844. }
  1845.  
  1846.  
  1847. DEFUN ("store-match-data", Fstore_match_data, Sstore_match_data, 1, 1, 0,
  1848.   "Set internal data on last search match from elements of LIST.\n\
  1849. LIST should have been created by calling `match-data' previously.")
  1850.   (list)
  1851.      Lisp_Object list;
  1852. {
  1853.   /* !!#### This function has not been Mule-ized */
  1854.   int i;
  1855.   Lisp_Object marker;
  1856.  
  1857.   if (!CONSP (list) && !NILP (list))
  1858.     list = wrong_type_argument (Qconsp, list);
  1859.  
  1860.   /* Unless we find a marker with a buffer in LIST, assume that this 
  1861.      match data came from a string.  */
  1862.   last_thing_searched = Qt;
  1863.  
  1864. #ifdef EMACS19_REGEXP
  1865.   /* Allocate registers if they don't already exist.  */
  1866.   {
  1867.     int length = XINT (Flength (list)) / 2;
  1868.  
  1869.     if (length > search_regs.num_regs)
  1870.       {
  1871.     if (search_regs.num_regs == 0)
  1872.       {
  1873.         search_regs.start
  1874.           = (regoff_t *) xmalloc (length * sizeof (regoff_t));
  1875.         search_regs.end
  1876.           = (regoff_t *) xmalloc (length * sizeof (regoff_t));
  1877.       }
  1878.     else
  1879.       {
  1880.         search_regs.start
  1881.           = (regoff_t *) xrealloc (search_regs.start,
  1882.                        length * sizeof (regoff_t));
  1883.         search_regs.end
  1884.           = (regoff_t *) xrealloc (search_regs.end,
  1885.                        length * sizeof (regoff_t));
  1886.       }
  1887.  
  1888.     re_set_registers (&searchbuf, &search_regs, length,
  1889.               search_regs.start, search_regs.end);
  1890.       }
  1891.   }
  1892. #endif /* EMACS19_REGEXP */
  1893.  
  1894.   for (i = 0; i < SEARCH_NREGS (&search_regs); i++)
  1895.     {
  1896.       marker = Fcar (list);
  1897.       if (NILP (marker))
  1898.     {
  1899.       search_regs.start[i] = -1;
  1900.       list = Fcdr (list);
  1901.     }
  1902.       else
  1903.     {
  1904.       if (MARKERP (marker))
  1905.         {
  1906.           if (XMARKER (marker)->buffer == 0)
  1907.         marker = Qzero;
  1908.           else
  1909.         XSETBUFFER (last_thing_searched,
  1910.                        XMARKER (marker)->buffer);
  1911.         }
  1912.  
  1913.       CHECK_INT_COERCE_MARKER (marker, 0);
  1914.       search_regs.start[i] = XINT (marker);
  1915.       list = Fcdr (list);
  1916.  
  1917.       marker = Fcar (list);
  1918.       if (MARKERP (marker)
  1919.           && XMARKER (marker)->buffer == 0)
  1920.         marker = Qzero;
  1921.  
  1922.       CHECK_INT_COERCE_MARKER (marker, 0);
  1923.       search_regs.end[i] = XINT (marker);
  1924.     }
  1925.       list = Fcdr (list);
  1926.     }
  1927.  
  1928.   return Qnil;  
  1929. }
  1930.  
  1931. /* Quote a string to inactivate reg-expr chars */
  1932.  
  1933. DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
  1934.   "Return a regexp string which matches exactly STRING and nothing else.")
  1935.   (str)
  1936.      Lisp_Object str;
  1937. {
  1938.   /* !!#### This function has not been Mule-ized */
  1939.   Bufbyte *in, *out, *end;
  1940.   Bufbyte *temp;
  1941.  
  1942.   CHECK_STRING (str, 0);
  1943.  
  1944.   temp = (Bufbyte *) alloca (string_length (XSTRING (str)) * 2);
  1945.  
  1946.   /* Now copy the data into the new string, inserting escapes. */
  1947.  
  1948.   in = string_data (XSTRING (str));
  1949.   end = in + string_length (XSTRING (str));
  1950.   out = temp; 
  1951.  
  1952.   for (; in != end; in++)
  1953.     {
  1954.       if (*in == '[' || *in == ']'
  1955.       || *in == '*' || *in == '.' || *in == '\\'
  1956.       || *in == '?' || *in == '+'
  1957.       || *in == '^' || *in == '$')
  1958.     *out++ = '\\';
  1959.       *out++ = *in;
  1960.     }
  1961.  
  1962.   return make_string (temp, out - temp);
  1963. }
  1964.  
  1965. #ifdef MULE_REGEXP
  1966.  
  1967. DEFUN ("re-compile", Fre_compile, Sre_compile, 1, 1, 0,
  1968.   "Compile REGEXP by GNU Emacs original regexp compiler,\n\
  1969. and return information of the compiled code by a vector of length 11:\n\
  1970.  [ COMPILED-PATTERN (string)\n\
  1971.    RE-NSUB REGS-ALLOCATED CAN-BE-NULL NEWLINE-ANCHOR (integers)\n\
  1972.    NO-SUB NOT-BOL NOT-EOL SYNTAX (integers)\n\
  1973.    FASTMAP TRANSLATE (string) ].\n\
  1974. If REGEXP is nil, just return the information of previously compiled code.")
  1975.   (regexp)
  1976.      Lisp_Object regexp;
  1977. {
  1978.   Lisp_Object val;
  1979.  
  1980.   if (! NILP (regexp))
  1981.     {
  1982.       CHECK_STRING (regexp, 0);
  1983.       last_regexp = Qnil;
  1984.       compile_pattern (regexp, &searchbuf, &search_regs,
  1985.                (!NILP (current_buffer->case_fold_search)
  1986.             ? DOWNCASE_TABLE : 0),
  1987.                0);
  1988.       re_compile_fastmap (&searchbuf);
  1989.     }
  1990.  
  1991.   val = Fmake_vector (11, Qnil);
  1992.   XVECTOR (val)->contents[0] = make_string (searchbuf.buffer, searchbuf.used);
  1993.   XVECTOR (val)->contents[1] = make_number (searchbuf.re_nsub);
  1994.   XVECTOR (val)->contents[2] = make_number (searchbuf.regs_allocated);
  1995.   XVECTOR (val)->contents[3] = make_number (searchbuf.can_be_null);
  1996.   XVECTOR (val)->contents[4] = make_number (searchbuf.newline_anchor);
  1997.   XVECTOR (val)->contents[5] = make_number (searchbuf.no_sub);
  1998.   XVECTOR (val)->contents[6] = make_number (searchbuf.not_bol);
  1999.   XVECTOR (val)->contents[7] = make_number (searchbuf.not_eol);
  2000.   XVECTOR (val)->contents[8] = make_number (searchbuf.syntax);
  2001.   if (searchbuf.fastmap_accurate && searchbuf.fastmap)
  2002.     XVECTOR (val)->contents[9] = make_string (searchbuf.fastmap, 256);
  2003.   if (searchbuf.translate)
  2004.     XVECTOR (val)->contents[10] = make_string (searchbuf.translate, 256);
  2005.  
  2006.   return val;
  2007. }
  2008.  
  2009. #endif
  2010.  
  2011.  
  2012. /************************************************************************/
  2013. /*                            initialization                            */
  2014. /************************************************************************/
  2015.  
  2016. void
  2017. syms_of_search (void)
  2018. {
  2019.  
  2020.   deferror (&Qsearch_failed, "search-failed", "Search failed", 1);
  2021.   deferror (&Qinvalid_regexp, "invalid-regexp", "Invalid regexp", 1);
  2022.  
  2023. #ifdef MULE_REGEXP
  2024.   defsubr (&Sre_compile);
  2025. #endif /* MULE_REGEXP */
  2026.  
  2027.   defsubr (&Sstring_match);
  2028.   defsubr (&Slooking_at);
  2029.   defsubr (&Sskip_chars_forward);
  2030.   defsubr (&Sskip_chars_backward);
  2031.   defsubr (&Sskip_syntax_forward);
  2032.   defsubr (&Sskip_syntax_backward);
  2033.   defsubr (&Ssearch_forward);
  2034.   defsubr (&Ssearch_backward);
  2035.   defsubr (&Sword_search_forward);
  2036.   defsubr (&Sword_search_backward);
  2037.   defsubr (&Sre_search_forward);
  2038.   defsubr (&Sre_search_backward);
  2039.   defsubr (&Sreplace_match);
  2040.   defsubr (&Smatch_beginning);
  2041.   defsubr (&Smatch_end);
  2042.   defsubr (&Smatch_data);
  2043.   defsubr (&Sstore_match_data);
  2044.   defsubr (&Sregexp_quote);
  2045. }
  2046.  
  2047. void
  2048. vars_of_search (void)
  2049. {
  2050.   /* !!#### This function has not been Mule-ized */
  2051.   searchbuf.allocated = 100;
  2052. #ifdef EMACS19_REGEXP
  2053.   searchbuf.buffer = (unsigned char *) xmalloc (searchbuf.allocated);
  2054. #else
  2055.   searchbuf.buffer = (char *) xmalloc (searchbuf.allocated);
  2056. #endif
  2057.   searchbuf.fastmap = search_fastmap;
  2058.  
  2059. #ifdef MULE_REGEXP
  2060. #ifdef EMULATE_EMACS19
  2061.   search_regs.num_regs = RE_NREGS;
  2062. #endif /* EMULATE_EMACS19 */
  2063.  
  2064.   for (i = 0; i <= MAXWORDBUF; i++)
  2065.     wordbuf[i] = (struct re_pattern_buffer *)0;
  2066. #endif /* MULE_REGEXP */
  2067.  
  2068.   last_regexp = Qnil;
  2069.   staticpro (&last_regexp);
  2070.  
  2071.   last_thing_searched = Qnil;
  2072.   staticpro (&last_thing_searched);
  2073.  
  2074. #ifdef MULE_REGEXP
  2075.   DEFVAR_LISP ("forward-word-regexp", &Vforward_word_regexp,
  2076.     "*Regular expression to be used in forward-word.");
  2077.   Vforward_word_regexp = Qnil;
  2078.  
  2079.   DEFVAR_LISP ("backward-word-regexp", &Vbackward_word_regexp,
  2080.     "*Regular expression to be used in backward-word.");
  2081.   Vbackward_word_regexp = Qnil;
  2082.  
  2083.   DEFVAR_INT ("regexp-version", &Vregexp_version,
  2084.     "version number of system internal regexp compiler and interpreter.");
  2085.   Vregexp_version = 0;
  2086. #ifdef EMACS18_REGEXP
  2087.   Vregexp_version = 18;
  2088. #endif /* EMACS18_REGEXP */
  2089. #ifdef EMACS19_REGEXP
  2090.   Vregexp_version = 19;
  2091. #endif /* EMACS19_REGEXP */
  2092. #endif /* MULE_REGEXP */
  2093. }
  2094.